import {
    reqUserLogin,
    reqUserLogout
} from '@/api';
import { Message } from 'element-ui';

const state = {
    userInfo: {
        name: localStorage.getItem('name'),
        token: localStorage.getItem('token')
    }
}

const actions = {
    // 1 实现用户登录
    async userLogin({
        commit
    }, user) {
        const result = await reqUserLogin(user)
        if (result.code === 200) {
            commit('SAVE_USER_INFO', result.data)
            return true
        } else {
            console.log(result.message);
        }
    },
    // 2 用户退出
    async logout({
        commit
    }) {
        const result = await reqUserLogout()
        if (result.code === 200) {
            // 清除vuex中数据
            commit('REMOVE_USER_INFO')
            Message.success('退出成功')
            // 清除本地数据
            localStorage.removeItem('name')
            localStorage.removeItem('token')
        } else {
            console.log(result.message);
        }
    }
}

const mutations = {
    // 1 存储用户登录内容
    SAVE_USER_INFO(state, userInfo) {
        state.userInfo.name = userInfo.name
        state.userInfo.token = userInfo.token
        // 为了有一个更好的用户体验，在用户刷新页面的时候，也会有token
        // 此时可以在本地存储当中也存储一份
        localStorage.setItem('name', userInfo.name)
        localStorage.setItem('token', userInfo.token)
    },
    // 2 清空状态管理中的数据
    REMOVE_USER_INFO(state) {
        state.userInfo.name = ''
        state.userInfo.token = ''
    }
}

const getters = {}

export default {
    namespaced: true,
    state,
    actions,
    mutations,
    getters
}